<!-- 我的 - 个人主页 -->
<template>
  <view>
    <z-paging-list ref="list" v-model="state.list" :refresher-enabled="state.currentId != 0"
      emptyImage="/static/images/empty/img_empty_service.png" :loading-more-enabled="state.currentId != 0"
      :safe-area-inset-bottom="false" @loadData="loadData">
      <template #top>
        <!-- <z-navbar title="" :border-bottom="false" bg-color="transparent" @back="refreshPrePage('loadData', 1)"></z-navbar> -->
        <view class="relative w-full h-490">
          <!-- 背景图 -->
          <view class='relative'>
            <view :class="['w-full h-490 absolute left-0 top-0 z-2', state.detailData?.background_image ? 'mask' : '']">
            </view>
            <view class="w-full h-490 absolute left-0 top-0 z-1">
              <u-image width="100%" height="100%"
                :src="state.detailData?.background_image ? state.detailData?.background_image : '/static/images/user/ic_def_background.png'" />
            </view>
          </view>
          <view class="w-full h-490 absolute left-0 top-0 z-2 flex flex-col">
            <view class="flex items-center pl-4"
              :style="{ height: backIconHeight + 'px', marginTop: backIconTop + 'px' }">
              <image class="z-2 w-18 h-34" src="/static/images/user/ic_back.png" @click="onBack" />
            </view>
            <view class="flex-1 flex flex-col w-full">
              <!-- 个人信息 -->
              <view class="w-full flex pt-4" :class="[state.isAdviser ? 'h-244' : 'h-190']">
                <view class="flex-1 flex items-center">
                  <view class="relative w-116 h-116 ml-8 mr-4">
                    <u-image width="100%" height="100%" shape="circle" :src="state.detailData?.avatar" />
                    <!-- <image v-if="state.detailData?.is_self" class="absolute bottom-0 right-0 z-2 w-40 h-40"
                      src="/static/images/user/ic_edit.png"
                      @click="navigate(`/package_user/pages/mine/info?isAdviser=${state.isAdviser}`)" /> -->
                  </view>
                  <view class="flex flex-col justify-center">
                    <view class="flex items-center h-50">
                      <view class="flex-shrink-0 mr-2 c-white text-32 font-bold  text-single">{{
                        state.detailData?.nickname }}
                      </view>
                      <view v-if="state.isAdviser" class="flex-shrink-0 tag-identity mr-2">顾问</view>
                      <image v-if="state.detailData?.vip_level > 0" mode="aspectFit"
                        :class="[state.detailData?.vip_level > 1 ? 'w-140 h-40' : 'w-112 h-28']"
                        :src="`/static/images/user/ic_vip_tag_${vipIcon}.png`" />
                    </view>

                    <view v-if="state.isAdviser" class="flex c-white text-24 mt-1">
                      <view class="mr-8">IP：{{ state.detailData?.ip_address || '-' }}</view>
                      <view>服务企业数量：{{ state.detailData?.club_number || '-' }}</view>
                    </view>
                    <view v-else class="flex c-white text-24 mt-1">
                      ID：{{ state.detailData?.userId }}
                      <view class="ml-2 px-1.5 rounded-full c-#fff text-24 border-copy" @click="copyText(state.detailData?.userId)">复制</view>
                    </view>
                  </view>
                </view>
                <!-- 只有自己显示 -->
                <view v-if="state.detailData?.is_self" class="flex-shrink-0 btn-edit absolute right-30"
                  @click="navigate(`/package_user/pages/mine/info?isAdviser=${state.isAdviser}`)">编辑个人信息
                </view>
              </view>
              <view v-if="!state.isAdviser" class="c-#fff text-24 px-8 mb-3 text-lines-3">{{ state.detailData?.introduce
              }}</view>
              <!-- 主体 -->
              <viwe class="flex-1 flex flex-col w-full content-card relative z-2">
                <u-tabs bg-color="none" :is-scorll="false" :list="state.tabList" bar-height="6" bar-width="30"
                  active-color="#333" inactive-color="#999" font-size="32" :bar-style="barStyle"
                  v-model="state.currentIndex" @change="onTabChange"></u-tabs>
                <view class="bar h-2 bg-#eee w-full"></view>
              </viwe>
            </view>
          </view>
        </view>
      </template>
      <!-- 简介 只有顾问有 -->
      <view v-if="state.currentId == 0 && state.isAdviser" class="px-4">
        <view class="intro-item">
          <image class="w-34 h-34" src="/static/images/user/ic_intro1.png" />
          <view class="mx-2">公司：</view>
          <view class="flex-1 text-single c-#666">{{ state.detailData?.intro?.company_name }}</view>
        </view>
        <view class="intro-item">
          <image class="w-34 h-34" src="/static/images/user/ic_intro2.png" />
          <view class="mx-2">职位：</view>
          <view class="c-#666">{{ state.detailData?.intro?.position }}</view>
        </view>
        <view class="intro-item">
          <image class="flex-shrink-0 w-34 h-34" src="/static/images/user/ic_intro3.png" />
          <view class="flex-shrink-0 mx-2">擅长领域：</view>
          <view class="flex flex-wrap">
            <view v-for="(item, index) in state.detailData?.intro?.expertise" :key="index" class="tag-field mr-1 my-1">{{
              item }}</view>
          </view>
        </view>
        <view class="intro-item">
          <image class="w-34 h-34" src="/static/images/user/ic_intro2.png" />
          <view class="mx-2">课程主题：</view>
          <view class="flex-1 text-single c-#666">{{ state.detailData?.intro?.course_theme }}</view>
        </view>
        <view class="intro-item" style="align-items: flex-start;">
          <image class="flex-shrink-0 w-34 h-34" src="/static/images/user/ic_intro2.png" />
          <view></view>
          <view class="flex-shrink-0 mx-2">介绍：</view>
          <view class="flex-1">{{ state.detailData?.intro?.self_desc }}</view>
        </view>

        <view class="intro-item" style="align-items: flex-start;">
          <view class="mx-5" v-for="(item, index) in state.detailData?.intro?.banner" :key="index">
            <u-image mode="widthFix" width="646" border-radius="20" :src='item' />
          </view>
        </view>

      </view>
      <view v-if="state.currentId == 1 && !state.history_lock">
        <u-swipe-action :show="item.show" bg-color="transparent" v-for="(item, index) in state.list" :key="index" :index="index"
          btn-width="80" :options="options" @click="onClick" @open="open">
          <view class="w-750">
            <drygood-item :data="item.article"></drygood-item>
          </view>
        </u-swipe-action>

        <!-- <drygood-item v-for="(item, index) in state.list" :key=index  :data="item.article"></drygood-item> -->
      </view>
      <view v-if="state.currentId == 1 && state.history_lock"
        class="flex flex-col items-center px-4 pt-20 c-#333 text-28">
        <image class="w-368 h-368" src="/static/images/empty/img_empty_service.png" />
        <view class="mt-5">用户设置了隐私保护，浏览记录不对外开放</view>
      </view>
      <!-- 我的学社 -->
      <view v-if="state.currentId == 2 && !state.club_lock" class="px-4 pt-2">
        <society-item v-for="(item, index) in state.list" :key=index :data="item"
          :is_self="state.detailData.is_self"></society-item>
      </view>
      <view v-if="state.currentId == 2 && state.club_lock" class="flex flex-col items-center px-4 pt-20 c-#333 text-28">
        <image class="w-368 h-368" src="/static/images/empty/img_empty_service.png" />
        <view class="mt-5">用户设置了隐私保护，加入的学社不对外开放</view>
      </view>
    </z-paging-list>
  </view>
</template>

<script setup>
import { navigate, showToast, copyText } from "@/common/util/uni";
import { uploadUrl } from '@/common/config/config'
import { vipLevels } from '@/common/constant/society.js'
import { useUserStore } from '@/store/user.js'
import { getUserHomepage, postUserEditBackground, getUserHistory, getUserClub, postHistoryDel } from '@/common/http/module/center.js'
import { refreshPrePage } from '@/common/util/util'

const userStore = useUserStore()
const list = ref();
const state = reactive({
  user_id: null, // 其他页面传的访问用户id
  history_lock: '', // 浏览记录不公开
  club_lock: '', // 我的学社不公开
  detailData: '', // 简介数据
  isAdviser: false, // 是否为顾问
  tabList: [],
  currentIndex: 0,
  currentId: 0,
  list: []
});

const options = [{
  text: '删除',
  style: {
    backgroundColor: '#FF513A',
    borderRadius: '12rpx',
    marginTop: '20rpx',
    marginBottom: '20rpx',
  }
}]

const barStyle = {
  // color
  backgroundColor: '#F4AF22'
}
const backIconTop = uni.getMenuButtonBoundingClientRect().top
const backIconHeight = uni.getMenuButtonBoundingClientRect().height

const vipIcon = computed(() => vipLevels.find(v => v.value == state.detailData?.vip_level)?.icon)

function open(index) {
  console.log(state.list,"kkkkkkk")
  state.list[index].show = true;
  state.list.map((val, idx) => {
    if (index != idx) state.list[idx].show = false;
  })
}

function onClick(index) {
  postHistoryDel(state.list[index].article_id).then(() => {
    showToast('删除成功')
    refresh()
  })

}
// 返回
function onBack() {
  refreshPrePage('loadData', 1)
  uni.navigateBack()
}

// tab切换
function onTabChange(e) {
  state.currentIndex = e
  state.currentId = state.tabList[state.currentIndex]?.id
  refresh()
}

// 编辑背景图
function onEditBanner() {
  uni.chooseImage({
    count: 1,
    sourceType: ['album'],
    success: res => uploadUserBg(res),
  })
}

// 上传背景图
function uploadUserBg(res) {
  uni.uploadFile({
    url: uploadUrl,
    header: { token: userStore.token },
    filePath: res.tempFilePaths[0],
    name: 'file',
    success: res => {
      const data = JSON.parse(res.data)
      if (data.code != 1) {
        showToast('上传失败')
      }
      onEditBackground(data.data.fullurl)
    },
    fail: () => {
      showToast('上传失败')
    }
  })
}

// 修改背景图请求
function onEditBackground(url) {
  postUserEditBackground({ background_image: url }).then(() => {
    showToast('编辑成功')
    // loadDetail()
    loadData(1)
  })
}

function refresh() {
  list.value.onRefresh()
}

async function loadData(page) {
  // 此处需先获取主页详情 再进行tab其他请求
  const { data } = await getUserHomepage(state.user_id)
  state.detailData = data
  // 是否为顾问
  state.isAdviser = data && data.identity == 1
  if (state.isAdviser) {
    state.tabList = [
      { id: 0, name: '简介' },
      { id: 1, name: `浏览记录(${data.history})` },
      { id: 2, name: `${data.is_self ? '我' : 'TA'}的学社(${data.club_number})` }
    ]
  } else {
    state.tabList = [
      { id: 1, name: `浏览记录(${data.history})` },
      { id: 2, name: `${data.is_self ? '我' : 'TA'}的学社(${data.club_number})` }
    ]
  }
  state.currentId = state.tabList[state.currentIndex].id

  // 如果未开放且非本人不进行请求
  state.history_lock = !state.detailData.history_open && state.currentId == 1 && !state.detailData.is_self
  state.club_lock = !state.detailData.club_open && state.currentId == 2 && !state.detailData.is_self
  if (state.currentId == 0 || state.history_lock || state.club_lock) return
  const tabPostList = [
    { currentId: 0, postMethod: getUserHistory },
    { currentId: 1, postMethod: getUserClub },
  ]
  tabPostList[state.currentId - 1].postMethod(page, state.user_id).then((res)=> {
   res.data?.data.map(item => {
      item.show = false
    })
    console.log(res.data?.data,"kkkk")
    list.value.onLoadResult(page ? res.data?.data : []);
  })
}

onLoad(options => {
  // loadDetail()
  state.user_id = options.user_id ?? null
  loadData;
});

defineExpose({ loadData })
</script>

<style lang="scss" scoped>
.border-copy {
  border: 2rpx solid #fff;
}
.mask {
  background-color: black;
  opacity: 0.4;
}

:deep(.u-tabs) {
  padding: 0 60rpx;
  width: 100% !important;
}

:deep(.u-scroll-box) {
  display: flex;
}

:deep(.u-tab-item) {
  flex: 1;
}

.bar {
  margin-top: -8rpx;
}

.intro-item {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
  font-size: 28rpx;
  color: #333;
}

.tag-field {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  background-color: #E5E5E5;
  color: #8C8C8C;
  font-weight: 400;
  font-size: 24rpx;
}

.btn-edit {
  height: 40rpx;
  color: #fff;
  font-size: 24rpx;
  padding: 2rpx 18rpx;
  border-radius: 4rpx;
  border: 2rpx solid #FFFFFF;
}

.content-card {
  // min-height: 200rpx;
  border-radius: 12rpx 12rpx 0px 0px;
  background-color: #FFFFFF;
}
</style>
